package com.echo.boot.parsers.xml.dom;

import com.echo.boot.pojo.Books;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URL;
import java.util.ArrayList;

public class JavaxDomParsersXml {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        //获得实例工厂   *javax.xml.parsers.DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //获得解析  *javax.xml.parsers.DocumentBuilderFactory
        DocumentBuilder builder = factory.newDocumentBuilder();
        //获得document --解析xml文档   java.io.FileNotFoundException    *org.w3c.dom.Document
        URL url = JavaxDomParsersXml.class.getResource("/");
        Document document = builder.parse(url + "xml/bookStore.xml");  //指java项目的根路径下的文件
        NodeList bookList = document.getElementsByTagName("book");
        ArrayList<Books> list = new ArrayList<>();
        for (int i = 0; i < bookList.getLength(); i++) {
            Books book = new Books();
            Node item = bookList.item(i);
            // 强转为实现类
            Element ele = (Element) item;
            // 获取属性
            String id = ele.getAttribute("id");
            book.setId(id);
            // 获取节点
            NodeList nodes = ele.getChildNodes();
            for (int j = 0; j < nodes.getLength(); j++) {
                Node childNode = nodes.item(j);
                // 获取子节点的 名称
                String nodeName = childNode.getNodeName();
                if ("title".equals(childNode.getNodeName())) {
                    // 获取子节点的内容
                    book.setTitle(childNode.getTextContent());
                }
                if ("price".equals(childNode.getNodeName())) {
                    // 获取子节点的内容
                    book.setPrice(new BigDecimal(childNode.getTextContent()));
                }
            }
            list.add(book);
        }
        System.out.println(list);
    }
}
